package com.atguigu.gmall.product;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 李旭
 * @date 2021/10/10 15:57
 * @Description:
 */
public class CompletableFutureDemo2 {

    public static void main(String[] args) throws Exception {
        //1:创建新线程
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,//核心线程
                10,//最大线程
                5,// 闲置线程的存活时间  == 最大线程-核心线程
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                //工厂
                //拒绝策略
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //1:
/*        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            System.out.println("我是上一个任务");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "上任务返回值";
        },threadPoolExecutor).thenApplyAsync((t) -> {
            System.out.println("thenApplyAsync:t:" + t);
            return "当任务返回值";
        },threadPoolExecutor).whenCompleteAsync((t,u) -> {
            System.out.println("whenCompleteAsync:t:" + t);
        });*/

/*        我是上一个任务：
        thenApplyAsync:t:上任务返回值
        whenCompleteAsync:t:当任务返回值*/

        //2 :
/*        CompletableFuture.supplyAsync(() -> {
                System.out.println("我是上一个任务");
            return "上任务返回值";
        },threadPoolExecutor).thenAcceptAsync((t) -> {
            System.out.println("thenApplyAsync:t:" + t);
        },threadPoolExecutor).whenCompleteAsync((t,u) -> {
            System.out.println("whenCompleteAsync:t:" + t);
        });*/


  /*      CompletableFuture.supplyAsync(() -> {
            System.out.println("我是上一个任务");
            return "上任务返回值";
        },threadPoolExecutor).thenRunAsync(() -> {
            System.out.println("我是当前任务:t:");
        },threadPoolExecutor).whenCompleteAsync((t,u) -> {
            System.out.println("whenCompleteAsync:t:" + t);
        });*/

        CompletableFuture<String> oneCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("我是上一个任务");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "123";
        });
        CompletableFuture<String> twoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("我是当前任务");
            return "456";
        });

        //等待所有子线程执行完成 我就继续执行主线程
        CompletableFuture.allOf(oneCompletableFuture, twoCompletableFuture).join();
        //CompletableFuture.anyOf();//等待任意一个子线程执行完成 我就继续执行主线程

        //多任务组合

        System.out.println("我是神龙");

    }

}
